﻿static class ListNodeExtensions
{
    public static IEnumerable<int> MergeAsEnumerable(this ListNode[] listNodes)
    {
        foreach (var node in listNodes)
        {
            for (var current = node; current != null; current = current.next)
                yield return current.val;
        }
    }
    public static ListNode? ToListNodes(this IEnumerable<int> ints)
    {
        ListNode listNode = new ListNode();
        ListNode? last = null;
        var current = listNode;
        foreach (var item in ints)
        {
            current.val = item;
            last = current;
            current = current.next = new ListNode();
        }
        if (last != null)
        {
            last.next = null;
            return listNode;
        }
        else
            return null;
    }
}

/// <summary>
/// https://leetcode-cn.com/problems/merge-k-sorted-lists/
/// </summary>
public class Solution
{
    public ListNode? MergeKLists(ListNode[] lists)
    {
        return lists.MergeAsEnumerable().OrderBy(item => item).ToListNodes();
    }
}